// 文件管理

// 处理文件上传
async function handleFileUpload(input, section) {
    const files = Array.from(input.files);
    if (!files.length) return;

    // 验证文件
    for (const file of files) {
        if (!ALLOWED_FILE_TYPES.includes(file.type)) {
            showMessage(`${file.name} 格式不支持`, 'error');
            input.value = '';
            return;
        }
        if (file.size > MAX_FILE_SIZE) {
            showMessage(`${file.name} 超过10MB`, 'error');
            input.value = '';
            return;
        }
    }

    // 初始化存储
    if (!window.fileStorage[section]) {
        window.fileStorage[section] = [];
    }

    // 添加文件
    files.forEach(file => {
        window.fileStorage[section].push({
            file: file,
            name: file.name,
            type: file.type
        });
    });

    // 更新预览
    updatePreview(section);
    input.value = '';
    showMessage(`已添加 ${files.length} 个文件`, 'success');
}

// 更新预览
function updatePreview(section) {
    const files = window.fileStorage[section] || [];
    const index = MATERIAL_SECTIONS.indexOf(section) + 1;
    const preview = document.getElementById(`preview-${index}`);

    if (!preview) return;

    preview.innerHTML = '';

    files.forEach((fileData, i) => {
        const div = document.createElement('div');
        div.className = 'file-item';

        if (fileData.type.startsWith('image/')) {
            const reader = new FileReader();
            reader.onload = e => {
                div.innerHTML = `
                    <img src="${e.target.result}">
                    <div class="file-name">${fileData.name}</div>
                    <button class="file-remove" onclick="removeFile('${section}', ${i})">×</button>
                `;
            };
            reader.readAsDataURL(fileData.file);
        } else {
            div.innerHTML = `
                <div class="pdf-icon">📄</div>
                <div class="file-name">${fileData.name}</div>
                <button class="file-remove" onclick="removeFile('${section}', ${i})">×</button>
            `;
        }

        preview.appendChild(div);
    });
}

// 删除文件
function removeFile(section, index) {
    if (window.fileStorage[section]) {
        window.fileStorage[section].splice(index, 1);
        updatePreview(section);
        showMessage('已删除', 'info');
    }
}